package com.suny.sf_server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.suny.DataDicVal.vo.DataDicValSelectVO;
import com.suny.constant.RedisKeyConstant;
import com.suny.result.ResponseCode;
import com.suny.sf_server.mapper.DataDicMapper;
import com.suny.sf_server.redis.IRedisService;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import com.suny.DataDicVal.DataDicVal;
import com.suny.sf_server.service.DataDicValService;
import com.suny.sf_server.mapper.DataDicValMapper;
import org.springframework.stereotype.Service;
import com.suny.DataDicVal.dto.DataDicValDTO;
import com.suny.DataDicVal.dto.DataDicValQueryDTO;
import com.suny.DataDicVal.vo.DataDicValVO;
import com.suny.result.PageDTO;
import com.suny.utils.BeanConverter;
import com.suny.exception.BusinessException;

import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.List;

/**
 * @author sun
 * @description 针对表【data_dic_val(数据字典值表)】的数据库操作Service实现
 * @createDate 2024-12-27 10:45:10
 */
@Service
@Slf4j
public class DataDicValServiceImpl extends ServiceImpl<DataDicValMapper, DataDicVal>
        implements DataDicValService {
    @Resource
    private ValidationService validationService;
    @Resource
    private DataDicMapper dataDicMapper;
    @Resource
    private IRedisService redisService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean addDataDicVal(DataDicValDTO dataDicValDTO) {
        if (dataDicValDTO == null || StringUtils.isBlank(dataDicValDTO.getValValue()) || dataDicValDTO.getDicId() == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        //根据id查询该id下是否存在同名字典值
        LambdaQueryWrapper<DataDicVal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDicVal::getDicId, dataDicValDTO.getDicId())
                .eq(DataDicVal::getValValue, dataDicValDTO.getValValue());
        if (baseMapper.selectCount(wrapper) > 0) {
            throw new BusinessException("该字典值已存在");
        }
        //dic_id校验是否有数据字典
        List<Integer>  dicIds =dataDicMapper.getHasDataDic();
        if (!dicIds.contains(dataDicValDTO.getDicId())) {
            throw new BusinessException("数据字典不存在");
        }

        DataDicVal dataDicVal = new DataDicVal();
        dataDicVal.setValValue(dataDicValDTO.getValValue());
        dataDicVal.setDicId(dataDicValDTO.getDicId());
        dataDicVal.setStatus(1);
        dataDicVal.setCreateTime(new Date());
        dataDicVal.setUpdateTime(new Date());
        
        int count = baseMapper.insert(dataDicVal);
        if (count == 0) {
            throw new BusinessException("添加失败");
        }
        
        // 清除相关缓存
        clearCache(dataDicValDTO.getDicId());
        return true;
    }

    @Override
    public Page<DataDicValVO> listDataDicVal(Integer dicId, PageDTO pageDTO) {
        // 1. 参数校验
        if (dicId == null || pageDTO == null || pageDTO.getPageNumber() <= 0 || pageDTO.getPageSize() <= 0) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }

        // 2. 生成包含分页参数的缓存key
        String cacheKey = String.format("%s:%d:%d:%d",
                RedisKeyConstant.DIC_VAL_LIST,
                dicId,
                pageDTO.getPageNumber(),
                pageDTO.getPageSize());

        // 3. 尝试从缓存获取
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }

        // 4. 查询数据库
        Page<DataDicVal> page = new Page<>(pageDTO.getPageNumber(), pageDTO.getPageSize());
        LambdaQueryWrapper<DataDicVal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDicVal::getDicId, dicId)
                .orderByDesc(DataDicVal::getCreateTime);
        Page<DataDicVal> dataDicValPage = this.page(page, wrapper);

        // 5. 转换为VO对象
        Page<DataDicValVO> dicValVOPage = new Page<>();
        dicValVOPage.setRecords(BeanConverter.convertList(dataDicValPage.getRecords(), DataDicValVO.class));
        dicValVOPage.setTotal(dataDicValPage.getTotal());
        dicValVOPage.setCurrent(dataDicValPage.getCurrent());
        dicValVOPage.setSize(dataDicValPage.getSize());

        // 6. 处理空结果缓存
        if (dicValVOPage != null && dicValVOPage.getTotal() > 0) {
            redisService.setValue(cacheKey, dicValVOPage, RedisKeyConstant.CACHE_TIME);
        } else {
            redisService.setValue(cacheKey, dicValVOPage, RedisKeyConstant.EMPTY_CACHE_TIME);
        }

        return dicValVOPage;
    }


    @Override
    public Page<DataDicValVO> getListByQuery(DataDicValQueryDTO dto) {
        String cacheKey = RedisKeyConstant.DIC_VAL_PREFIX + "query:" + dto.hashCode()+":"+dto.getPageNumber() + ":" + dto.getPageSize();
        if (redisService.isExists(cacheKey)) {
            return redisService.getValue(cacheKey);
        }

        Page<DataDicVal> page = new Page<>(dto.getPageNumber(), dto.getPageSize());
        
        LambdaQueryWrapper<DataDicVal> wrapper = new LambdaQueryWrapper<>();

        wrapper.like(StringUtils.isNotBlank(dto.getValValue()), DataDicVal::getValValue, dto.getValValue())
                .eq(StringUtils.isNotBlank(dto.getDicId()), DataDicVal::getDicId, dto.getDicId())
                .eq(dto.getStatus() != null, DataDicVal::getStatus, dto.getStatus());
        Page<DataDicVal> dataDicValPage = this.page(page, wrapper);
        Page<DataDicValVO> dicValVOPage = new Page<>();
        dicValVOPage.setRecords(BeanConverter.convertList(dataDicValPage.getRecords(), DataDicValVO.class));
        dicValVOPage.setTotal(dataDicValPage.getTotal());
        dicValVOPage.setCurrent(dataDicValPage.getCurrent());
        dicValVOPage.setSize(dataDicValPage.getSize());
        
        // 存入缓存
        redisService.setValue(cacheKey, dicValVOPage, RedisKeyConstant.CACHE_TIME);
        return dicValVOPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(Integer valId, Integer status) {
        if (valId == null || status == null) {
            throw new BusinessException(ResponseCode.ILLEGAL_PARAMETER.getInfo());
        }
        
        if (status != 1 && status != 0) {
            throw new BusinessException("状态值无效");
        }
        // 获取字典值所属的字典ID
        DataDicVal val = getById(valId);
        if (val == null) {
            throw new BusinessException("字典值不存在");
        }
        if (status.equals(val.getStatus())){
            throw new BusinessException("状态值未改变");
        }

        
        // 检查字典值是否已被引用（仅当停用时）
        if (status == 0 && validationService.isDataDicValReferenced(valId)) {
            throw new BusinessException("该字典值已被其他模块引用，不能停用");
        }
        
        LambdaQueryWrapper<DataDicVal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DataDicVal::getValId, valId);
        
        DataDicVal dataDicVal = new DataDicVal();
        dataDicVal.setUpdateTime(new Date());
        dataDicVal.setStatus(status);
        
        int count = baseMapper.update(dataDicVal, wrapper);
        if (count == 0) {
            throw new BusinessException("更新失败");
        }

        clearCache(val.getDicId());
        return true;
    }

    @Override
    public Boolean getHasDataDicVal(Integer dicId) {
        return validationService.hasDataDicVal(dicId);
    }

    @Override
    public Boolean getHasDataDicValID(Integer dicId) {
        return validationService.hasDataDicValID(dicId);
    }
    @Override
    public List<DataDicValSelectVO> getSelectByDicId() {
        String key= RedisKeyConstant.DIC_VAL_SELECT ;
        if (redisService.isExists(key)) {
            return redisService.getValue(key);
        }
        LambdaQueryWrapper<DataDicVal> wrapper = new LambdaQueryWrapper<>();
        wrapper.orderByDesc(DataDicVal::getCreateTime);
        wrapper.eq(DataDicVal::getDicId, 1);
        wrapper.eq(DataDicVal::getStatus, 1);
        List<DataDicVal> list = list(wrapper);
        if (list == null) {
            throw new BusinessException("没有数据字典值");
        }
        List<DataDicValSelectVO> vos = BeanConverter.convertList(list, DataDicValSelectVO.class);
        redisService.setValue(key, vos, RedisKeyConstant.CACHE_TIME);
        return vos;
    }

    /**
     * 清除数据字典值相关缓存
     */
    private void clearCache(Integer dicId) {
//        clearCache();
        redisService.removePattern(RedisKeyConstant.DIC_VAL_LIST +":"+ dicId+":*");
        // 清除所有查询缓存
        redisService.removePattern(RedisKeyConstant.DIC_VAL_PREFIX + "query:*");
        redisService.remove(RedisKeyConstant.DIC_VAL_SELECT );
    }


    /**
     * 清除字典值相关缓存
     */
    private void clearCache() {
        // 使用模式匹配删除所有字典值列表缓存
        redisService.removePattern(RedisKeyConstant.DIC+ ":*");
    }
}




